<template>
  <div>
    <div class="goods">
      <!-- 左边 -->
      <div class="menu-wrapper" ref="menuWrapper">
        <ul>
          <li class="menu-item" v-for="(item,index) in goods" :key="index" ref="menuList" :class="{'current':currentIndex===index}" @click="selectMenu(index,$event)">
            <!-- 当滚动的currentIndex和index相等时 -->
            <span class="text border-t-1px">
            <span class="icon" v-show="item.type>0" :class="classMap[item.type]"></span> {{item.name}}
            </span>
          </li>
        </ul>
      </div>
      <!-- 右边 -->
      <div class="foods-wrapper" ref="foodsWrapper">
        <ul>
          <li class="food-list" v-for="(item,index) in goods" :key="index" ref="foodList">
            <h1 class="title">{{item.name}}</h1>
            <ul>
              <li class="food-item border-1px" v-for="(food,index) in item.foods" :key="index" @click="selectFood(food,$event)">
                <div class="icon">
                  <img :src="food.icon" width="57" height="57">
                </div>
                <div class="content">
                  <h2 class="name">{{food.name}}</h2>
                  <p class="desc">{{food.description}}</p>
                  <div class="extra">
                    <span class="count">月销{{food.sellCount}}份</span>
                    <span class="count">好评率{{food.rating}}%</span>
                  </div>
                  <div class="price">
                    <span class="now">￥{{food.price}}</span>
                    <span class="old" v-show="food.oldPrice">￥{{food.oldPrice}}</span>
                  </div>
                  <div class="cartcontrol-wrapper">
                    <cartcontrol @add="addFood" :food="food"></cartcontrol>
                  </div>
                </div>
              </li>
            </ul>
          </li>
        </ul>
      </div>
      <shopcart ref="shopcart" :selectFoods="selectFoods" :deliveryPrice="seller.deliveryPrice" :minPrice="seller.minPrice" />
    </div>
    <food @add="addFood" :food="selectedFood" ref="food" />
  </div>
</template>
<script type="text/ecmascript-6">
import shopcart from '@/components/shopcart/shopcart';
import cartcontrol from '@/components/cartcontrol/cartcontrol';
import food from '@/components/food/food';
import BScroll from 'better-scroll';

const ERR_OK = 0;
const debug = process.env.NODE_ENV !== 'production';

export default {
  props: {
    seller: { // seller在App.vue <router-view :seller="seller">传入
      type: Object
    }
  },
  data() {
    return {
      goods: [],
      listHeight: [], // 储存右侧每个区间的高度
      scrollY: 0,
      selectedFood: {}
    };
  },
  computed: {
    // 计算属性，判断当前的位置
    currentIndex() {
      for (let i = 0; i < this.listHeight.length; i++) {
        let height1 = this.listHeight[i];
        let height2 = this.listHeight[i + 1];
        if (!height2 || (this.scrollY >= height1 && this.scrollY < height2)) {
          return i;
        }
      }
      return 0;
    },
    selectFoods() {
      let foods = [];
      this.goods.forEach((good) => {
        good.foods.forEach((food) => {
          if (food.count) {
            foods.push(food);
          }
        });
      });
      return foods;
    }
  },
  created() {
    this.classMap = ['decrease', 'discount', 'special', 'invoice', 'guarantee'];

    const url = debug ? '/api/goods' : 'http://ustbhuangyi.com/sell/api/goods';
    this.$http.get(url).then((response) => {
      response = response.body;
      console.log(response);
      if (response.errno === ERR_OK) {
        this.goods = response.data;
        this.$nextTick(() => { // 当计算和Domx先关的时候可以用 $nextTick 來确保Dom变化后再执行一些事情
          this._initScroll();
          this._calculateHeight(); // 计算右侧每个区间的高度
        });
      }
    });
  },
  methods: {
    // 传入索引index对应右侧,点击事件会执行两次event处理
    selectMenu(index, event) {
      if (!event._constructed) {
        return;
      };
      console.log(index);
      let foodList = this.$refs.foodList;
      let el = foodList[index];
      this.foodsScroll.scrollToElement(el, 300);
    },
    selectFood(food, event) {
      if (!event._constructed) {
        return;
      }
      this.selectedFood = food;
      this.$refs.food.show(); // 父组件获取子组件show方法
    },
    addFood(target) {
      this._drop(target);
    },
    _drop(target) {
      // 体验优化,异步执行下落动画
      this.$nextTick(() => {
        this.$refs.shopcart.drop(target); // 通过DOM节点shopcart实现父组件调用子组件drop方法
      });
    },
    _initScroll() {
      this.meunScroll = new BScroll(this.$refs.menuWrapper, {
        click: true
      });
      this.foodsScroll = new BScroll(this.$refs.foodsWrapper, {
        click: true,
        probeType: 3 // 探针作用，实时监测滚动位置。。probeType: 1：滚动的时候会派发scroll事件，会截流。2：滚动的时候实时派发scroll事件，不会截流。 3：除了实时派发scroll事件，在swipe的情况下仍然能实时派发scroll事件
      });
      // bscroll插件的一个监听事件scroll,设置监听滚动位置
      this.foodsScroll.on('scroll', (pos) => {
        if (pos.y <= 0) {
          // scrollY接收变量
          this.scrollY = Math.abs(Math.round(pos.y)); // abs绝对值，两位小数
        }
        // console.log(pos.y);
      });
    },
    _calculateHeight() {
      let foodList = this.$refs.foodList;
      let height = 0;
      this.listHeight.push(height); // 第一个高度
      for (let i = 0; i < foodList.length; i++) {
        let item = foodList[i];
        height += item.clientHeight;
        this.listHeight.push(height);
      }
    }
  },
  components: {
    shopcart,
    cartcontrol,
    food
  }
};

</script>
<style lang="scss" scoped="" type="text/css">
@import "../../common/stylus/mixin";

.goods {
  display: flex;
  position: absolute;
  top: 174px;
  bottom: 46px;
  width: 100%;
  overflow: hidden;
  .menu-wrapper {
    flex: 0 0 80px;
    width: 80px;
    background: #f3f3f7;
    .menu-item {
      display: table;
      height: 54px;
      width: 56px;
      padding: 0 12px;
      line-height: 14px;
      &.current {
        position: relative;
        z-index: 10;
        margin-top: -1px;
        background: #fff;
        font-weight: 700;
      }
      .text {
        @include border-none();
        .icon {
          display: inline-block;
          vertical-align: top;
          width: 12px;
          height: 12px;
          margin-right: 2px;
          background-size: 100% 100%;
          background-repeat: no-repeat;
          &.decrease {
            @include bg-image('decrease_3');
          }
          &.discount {
            @include bg-image('discount_3');
          }
          &.guarantee {
            @include bg-image('guarantee_3');
          }
          &.invoice {
            @include bg-image('invoice_3');
          }
          &.special {
            @include bg-image('special_3');
          }
        }
      }
      .text {
        display: table-cell;
        width: 56px;
        vertical-align: middle;
        @include border-t-1px(rgba(7, 17, 27, .1));
        font-size: 12px;
      }
    }
  }
  .foods-wrapper {
    flex: 1;
    .title {
      padding-left: 14px;
      height: 26px;
      line-height: 26px;
      border-left: 2px solid #d9dde1;
      font-size: 12px;
      color: rgb(147, 153, 159);
      background: #f3f5f7;
    }
    .food-item {
      display: flex;
      margin: 18px;
      padding-bottom: 18px;
      @include border-b-1px(rgba(7, 17, 27, .1));
      &.last-child {
        @include border-none();
        margin-bottom: 0;
      }
      .icon {
        flex: 0 0 0 57px;
        margin-right: 10px;
      }
      .content {
        flex: 1;
        .name {
          margin: 2px 0 8px 0;
          height: 14px;
          line-height: 14px;
          font-size: 14px;
          ;
          color: rgb(7, 17, 27);
        }
        .desc,
        .extra {
          line-height: 10px;
          font-size: 10px;
          color: rgb(147, 153, 159);
        }
        .desc {
          line-height: 12px;
          margin-bottom: 8px;
        }
        .extra {
          .count {
            margin-bottom: 12px;
          }
        }
        .price {
          font-weight: 700px;
          line-height: 24px;
          .now {
            margin-right: 8px;
            font-size: 14px;
            color: rgb(240, 20, 20);
          }
          .old {
            text-decoration: line-through;
            font-size: 10px;
            color: rgb(147, 153, 159);
          }
        }
        .cartcontrol-wrapper {
          position: absolute;
          right: 0;
          bottom: 12px;
        }
      }
    }
  }
}

</style>
